package com.fingard.dsp.bank.directbank.chinapay05;

import com.chinapay.secss.SecssConstants;
import com.chinapay.secss.SecssUtil;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IGateway;
import com.fingard.dsp.bank.directbank.chinapay01.util.AcpService;
import com.fingard.dsp.bank.directbank.chinapay01.util.SDKUtil;
import com.fingard.dsp.bank.reqrespobj.gateway.ReqGateway;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsQueryOrder;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;

import java.util.HashMap;
import java.util.Map;

/**
 * 中国银联网关支付
 * 
 * @author Cruise
 * @date 2018年8月21日
 */
public class ChinaPay05Gateway extends ChinaPay05Base implements IGateway {
	/**
	 * 银联网关支付下单
	 */
	@Override
	public HashMap<String, String> GenGwMap(ReqGateway p_reqGateway) throws Exception {
		HashMap<String, String> tmpRetMap = new HashMap<String, String>();

		try {
			String ownAct = p_reqGateway.reqHashMap.get("OurBankAccount");
			ActSetItem actItem = getBankConfig().getActSetItem(ownAct, "gateway");
			if (actItem != null) {
				Map<String, String> tmpMap = new HashMap<String, String>();
				tmpMap.put("Version","20150922");//版本号认证支付和快捷支付：20150922	其余：20140728
				tmpMap.put("AccessType","");//接入类型0：商户身份接入（默认）	1：机构身份接入
				tmpMap.put("InstuId","");//接入机构号
				tmpMap.put("AcqCode","");//收单机构号

				tmpMap.put("MerId",actItem.merchantId);//商户号

				tmpMap.put("MerOrderNo",p_reqGateway.reqHashMap.get("RdSeq"));//商户订单号

				String dateStart=p_reqGateway.reqHashMap.get("TimeStart");
				tmpMap.put("TranDate",dateStart.substring(0,8));//商户交易日期
				tmpMap.put("TranTime",dateStart.substring(8,14));//商户交易时间
				tmpMap.put("OrderAmt",StringHelper.amountMultiply100(p_reqGateway.reqHashMap.get("Amount")));//订单金额

                String tranType = "0001";
                String isPrivate = p_reqGateway.reqHashMap.get("IsPrivate");
                if (StringHelper.hasAnyChar(isPrivate) && !"1".equalsIgnoreCase(isPrivate)) {
                    tranType = "0002";
                }
				//无卡网银 0001  0004 快捷支付
				tmpMap.put("TranType",tranType);//交易类型
				tmpMap.put("BusiType","0001");//业务类型
				tmpMap.put("CurryNo","CNY");//交易币种
				tmpMap.put("SplitType","");//分账类型商户提交分账类交易时必填
				tmpMap.put("SplitMethod","");//分账方式商户提交分账类交易时必填
				tmpMap.put("MerSplitMsg","");//分账信息商户提交分账类交易时必填
				tmpMap.put("BankInstNo","");//支付机构号0005下单转账业务需要上送700000000000006
				tmpMap.put("MerPageUrl",actItem.returnURL);//商户前台通知地址
				tmpMap.put("MerBgUrl",actItem.notifyURL);//商户后台通知地址
				tmpMap.put("CommodityMsg",p_reqGateway.reqHashMap.get("Description"));//商品信息
				tmpMap.put("MerResv",p_reqGateway.reqHashMap.get("Attach"));//商户私有域
				tmpMap.put("TranReserved","");//交易扩展域
				tmpMap.put("CardTranData","");//有卡交易信息域分期数
				tmpMap.put("Term","");//分期数

				String diffMins=String.valueOf(DateHelper.getDifferMins(p_reqGateway.getTimeExpire(),p_reqGateway.getTimeStart()));

				if (diffMins.contains(".")) {

					diffMins = diffMins.substring(0, diffMins.indexOf("."));
				}
				tmpMap.put("PayTimeOut",diffMins );//支付超时时间

				tmpMap.put("TimeStamp","");//防钓鱼时间戳
				tmpMap.put("RemoteAddr",actItem.createIP);//防钓鱼客户浏览器IP风控数据
				tmpMap.put("RiskData","");//防钓鱼客户浏览器IP风控数据
				tmpMap.put("Signature","");//签名

				tmpMap = sortMap(tmpMap);

				SecssUtil secssUtil=getSecssUtil(actItem);

				secssUtil.sign(tmpMap);

				if (SecssConstants.SUCCESS.equals(secssUtil.getErrCode())) {
					tmpMap.put("Signature", secssUtil.getSign());
					tmpRetMap.put("RespCode", "0");
					tmpRetMap.put("RespInfo", "签名成功");
					String submitGatewayUrl = bankFront.getUrl("gatewayPay");
					WriteBankLogLn2("银联在线网关支付提交服务地址:" + submitGatewayUrl);
					String tmpHtmlRet = AcpService.createAutoFormHtml(submitGatewayUrl, tmpMap, getCharset());
					String tmpSignData = SDKUtil.coverMap2String(tmpMap);
					WriteBankLogLn2("发送请求数据:\r\n" + tmpSignData);
					tmpRetMap.put("Result", tmpHtmlRet);
				} else {
					tmpRetMap.put("RespCode", "-1");
					tmpRetMap.put("RespInfo", "签名失败，原因:" + secssUtil.getErrMsg());
				}

			} else {
				tmpRetMap.put("RespCode", "0");
				tmpRetMap.put("RespInfo", "未找到账号:[" + ownAct + "]商户配置信息!");
				tmpRetMap.put("Result", "");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetMap.put("RespCode", "-1");
			tmpRetMap.put("RespInfo", ex.getMessage());
			WriteBankLogLn(ex);
		}
		
		return tmpRetMap;
	}

	private Map<String, String> sortMap(Map<String, String> tmpMap) {
		Map<String, String> map = new HashMap<String, String>();
		for (Map.Entry<String, String> entry : tmpMap.entrySet()) {
			if (!"".equals(entry.getValue())) {
				map.put(entry.getKey(), entry.getValue());
			}
		}
		return map;
	}


	/**
	 * 网关支付状态查询
	 * 
	 * @param p_reqGateway
	 *            查询请求对象
	 * @return 查询响应对象
	 * @throws Exception
	 *             支付状态查询异常
	 */
	@Override
	public RetAtsQueryOrder queryGWPay(ReqQueryOrder p_reqGateway) throws Exception {
		RetAtsQueryOrder retAts = new RetAtsQueryOrder();
		retAts.rdSeq = p_reqGateway.rdSeq;
		
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_reqGateway.ownAct, "gateway");
			if (actItem != null) {
				Map<String, String> tmpQryReq = new HashMap<String, String>();

				tmpQryReq.put("Version", "20140728");
				tmpQryReq.put("AccessType", "0");
				tmpQryReq.put("InstuId", "");
				tmpQryReq.put("MerId", actItem.merchantId);//商户号
				tmpQryReq.put("MerOrderNo", p_reqGateway.rdSeq);// 商户订单号
				tmpQryReq.put("TranDate", Format.Date8Format.format(p_reqGateway.getBgnDateTime()));// 业务类型
				tmpQryReq.put("TranType", "0502");
				tmpQryReq.put("BusiType", "0001");// 接入类型，商户接入固定填0，不需修改
				tmpQryReq.put("TranReserved", "");
				tmpQryReq.put("Signature", "");

				WriteBankLogLn2("网关支付查询请求数据:\r\n" + SDKUtil.coverMap2String(tmpQryReq));
				SecssUtil secssUtil = getSecssUtil(actItem);
				secssUtil.sign(tmpQryReq);

				if (SecssConstants.SUCCESS.equals(secssUtil.getErrCode())) {
					tmpQryReq.put("Signature", secssUtil.getSign());
					WriteBankLogLn2("签名为" + secssUtil.getSign());
					String submitQryGatewayUrl = bankFront.getUrl("gatewayPayQuery");
					WriteBankLogLn2("网关支付状态查询服务地址:" + submitQryGatewayUrl);

					Map<String, String> tmpMapRet = AcpService.post(tmpQryReq, submitQryGatewayUrl, getCharset());
					if (tmpMapRet.size() > 0) {
						String tmpRespCode = tmpMapRet.get("respCode");
						if ("0000".equals(tmpRespCode)) {
							retAts.respCode = "0";
							retAts.respInfo = tmpMapRet.get("origRespMsg");
							retAts.outTransID = tmpMapRet.get("respMsg");
							retAts.rdSeq = tmpMapRet.get("MerOrderNo");
							retAts.transState = tmpMapRet.get("OrderStatus");
							retAts.payInfoCode = tmpMapRet.get("OrderStatus");
						} else {
							retAts.respCode = "-1";
							retAts.respInfo = tmpMapRet.get("respMsg");
						}
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = "银行响应数据为空!";
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = "签名失败" + secssUtil.getErrMsg();
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo="未找到账号:[" + p_reqGateway.ownAct + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		return retAts;
	}
}
